Exercise 24 練習24 <<
Previous Exercise 28 練習28
Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python max() function!
The goal of this exercise is to think about some internals that Python normally takes care of for us. All you need is some variables and if statements!
實現一個函數,將三個變量作為輸入,並返回三個變量中的最大值。 無需使用Python max()函數即可執行此操作!
本練習的目的是考慮Python通常為我們處理的一些內部組件。 您只需要一些變量和if語句!
solution 解決方案
Sample solutions
There are many ways to answer this question, ranging from simple to complex. Here are a few reader-submitted answers!
This first example solution uses a series of if statements and comparisons to find the largest of 3 elements.
有許多方法可以回答此問題,從簡單到復雜。 這是讀者提交的一些答案!
第一個示例解決方案使用一系列if語句和比較來查找3個元素中的最大元素。
def max_of_three(a,b,c):
max_3=0
if a>b:
#max_3=a
if a>c:
max_3=c
else:
max_3=a
else:
if b>c:
max_3=b
else:
max_3=c
return max_3
Another solution is a little bit less verbose, taking 3 numbers as an input, making them into
a list, sorting them, and then reading off the largest element.
This last solution uses a more compact series of if statement comparisons to cover all cases
of 3 elements.
另一個解決方案是稍微冗長一些,將3個數字作為輸入,將它們放入列表,對它們進行排序,然後讀取最大的元素。
最後一個解決方案使用一系列更緊湊的if語句比較來涵蓋3個元素的所有情況。
#!/usr/bin/env python
import sys
if len(sys.argv) < 4:
print 'Usage <value1> <value2> <value3>'
sys.exit ( 1 )
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
def maxfunction(a,b,c):
if (a > b) and (a > c):
print 'Max value is :',a
elif (b > a) and (b > c):
print 'Max value is :',b
elif (c > a) and (c > b):
print 'Max value is :',c
maxfunction(arg1,arg2,arg3)
Exercise 24 練習24 <<
Previous